package com.sy.auto.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenTemplate {
    @Autowired
    TokenProperties tokenProperties;

    /**
     * 生成token
     * @param payload 用户信息
     * @return token字符串
     */
    public String generateToken(Map<String, ?> payload) {
        return JWT.create()
                .withHeader(getHeader())
                .withExpiresAt(getExpireDate())
                .withPayload(payload)
                .sign(Algorithm.HMAC256(tokenProperties.getSecret()));
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public ValidResult validResult(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(tokenProperties.getSecret())).build();
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = jwtVerifier.verify(token);
        } catch (JWTDecodeException e) {
            return new ValidResult(0,"token无效",null);
        } catch (TokenExpiredException e){
            return new ValidResult(0,"token已失效",null);
        }
        return new ValidResult(1,"token有效",decodedJWT.getClaims());
    }
    Map getHeader() {
        Map map = new HashMap();
        map.put("typ", "jwt");
        map.put("alg", "HmacSHA256");
        return map;
    }

    Date getExpireDate() {
        long time = System.currentTimeMillis() + tokenProperties.getValidTime();
        return new Date(time);
    }
}
